import PubSub from 'pubsub-js'
import request from '../../utils/request'

//创建app实例
const appInstance = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay: false,
    song: {},
    musicId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //路由传参 通过options接收
    //路由传参 如果数据过长 会被截掉.
    let musicId = options.musicId
    this.setData({
      musicId
    })

    // console.log(musicId);
    this.getMusicInfo(musicId)
    if (appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === musicId) {
      this.setData({
        isPlay: true
      })
    }
    this.backAudioManager = wx.getBackgroundAudioManager();
    this.backAudioManager.onPlay(() => {
      this.changePlayState(true)
      appInstance.globalData.musicId = musicId
    })
    this.backAudioManager.onPause(() => {
      this.changePlayState(false)
    })
    this.backAudioManager.onStop(() => {
      console.log('stop');
      this.changePlayState(false)
    })
  },
  changePlayState(isPlay) {
    this.setData({
      isPlay
    })
    appInstance.globalData.isMusicPlay = isPlay
  },

  //获取song数据
  async getMusicInfo(musicId) {
    let songData = await request('/song/detail', { ids: musicId })
    this.setData({
      song: songData.songs[0]
    })

    //动态修改标题
    wx.setNavigationBarTitle({
      title: this.data.song.name
    })
  },

  //修改播放状态
  handleMusicPlay() {
    let isPlay = !this.data.isPlay
    // this.setData({
    //   isPlay
    // })
    this.musicControl(isPlay)
  },

  //控制音乐播放的功能函数
  async musicControl(isPlay) {
    //创建播放实例
    let { musicId, song } = this.data
    if (isPlay) {
      //获取播放链接
      let musicLinkData = await request('/song/url', { id: musicId })
      let musicLink = musicLinkData.data[0].url

      //创建播放实例
      this.backAudioManager.src = musicLink
      this.backAudioManager.title = song.name
    } else {
      this.backAudioManager.pause()
    }
  },

  handleSwitch(event) {
    let type = event.currentTarget.id
    PubSub.publish('switchType', type)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})